package com.example.com.skills_utf8;



import java.io.IOException;
import java.io.UnsupportedEncodingException;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.MifareUltralight;
import android.nfc.tech.NfcA;
import android.nfc.tech.NfcF;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

/**
 * An example of how to use the NFC foreground dispatch APIs. This will intercept any MIME data
 * based NDEF dispatch as well as all dispatched for NfcF tags.
 */
public class ForegroundDispatch_nfc extends Activity {
	
	private ForegroundDispatch_nfc activity = this;
	
    private NfcAdapter mAdapter;
    private PendingIntent mPendingIntent;
    private IntentFilter[] mFilters;
    private String[][] mTechLists;
    private TextView mText;
    private int mCount = 0;

    @Override
    public void onCreate(Bundle savedState) {
        super.onCreate(savedState);

        setContentView(R.layout.foreground_dispatch);
        mText = (TextView) findViewById(R.id.text);
        mText.setText("Scan a tag");

        mAdapter = NfcAdapter.getDefaultAdapter(this);

        // Create a generic PendingIntent that will be deliver to this activity. The NFC stack
        // will fill in the intent with the details of the discovered tag before delivering to
        // this activity.
        mPendingIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

        // Setup an intent filter for all MIME based dispatches
        IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        IntentFilter tech = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
        IntentFilter tag = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
        try {
            ndef.addDataType("*/*");
        } catch (MalformedMimeTypeException e) {
            throw new RuntimeException("fail", e);
        }
        mFilters = new IntentFilter[] {
                ndef,
                tech,
                tag
        };

        // Setup a tech list for all NfcF tags
        mTechLists = new String[][] { new String[] { NfcF.class.getName() } };
     
        
        
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mAdapter != null) mAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters,
                mTechLists);
    }

    @Override
    public void onNewIntent(Intent intent) {
        Log.i("Foreground dispatch", "Discovered tag with intent: " + intent);
        mText.setText("Discovered tag " + ++mCount + " with intent: " + intent);
        
        if(intent.getAction().equals(NfcAdapter.ACTION_NDEF_DISCOVERED)) //ndef
        {
        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        if (rawMsgs != null) {

        	NdefMessage[] msgs = new NdefMessage[rawMsgs.length];

            for (int i = 0; i < rawMsgs.length; i++) {

                msgs[i] = (NdefMessage) rawMsgs[i];

                
            }
            
            // 一个msg里包含多个Record  
            NdefRecord[] records = msgs[0].getRecords();
            NdefRecord record = records[0];
            if(records != null){
                try {
					String readResult = new String(record.getPayload(),"UTF-8");
					System.out.println(readResult);
					String tmp =mText.getText().toString();
					mText.setText( tmp + " 读取的内容: " + readResult);
					
					
					
					// 得到详细内容  
		        	Tag rawTag =intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
		        	if (rawTag != null) {
		            	 String[]temp = rawTag.getTechList();
		                 for(String s :temp){
		                   Log.i("xxx","s = "+s);
		                 }
		                 
		                
		                 // 难道只有MifareClassic能得到详细信息?
		                 NfcA nfcA =NfcA.get(rawTag);
		                 nfcA.connect();
		                 byte[] content =nfcA.getAtqa();  
		          //       StringBuffer sb = new StringBuffer();
		                 String sb ="";
		                 for(int i =0; i<content.length; i++){ 
		                	 int v = content[i] & 0xFF;
		                	 
		                	 String str_content ="";
		                	 str_content += Integer.toHexString(v);
		                	 if(str_content.length() < 2)
		                		 sb +=str_content;
		                	 else
		                		 sb = "0"+str_content;
		                 }
		                 System.out.println(sb);
		                 
		                 
		           /*      
		                 try {
							Class<?> c =Class.forName(temp[0]);
					//		MifareUltralight obj = (MifareUltralight)c.newInstance();
					//		obj.connect();
							
							
							
							
						} catch (ClassNotFoundException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
		                 catch (InstantiationException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IllegalAccessException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
		             */    
		                
		               
		                 /*
		                 // 这样并不能启动第三方程序,  要启动还是需要对方有对应处理,才能操作
		                 try {
							Intent another_intent = new Intent(
									activity,
									Class.forName(readResult) );
									
						} catch (ClassNotFoundException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
		                 */
		                 
		                 
		            }
					
					
					
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
            }
            
        
        	}
        
        }
        else if(intent.getAction().equals(NfcAdapter.ACTION_TECH_DISCOVERED)) { //tech
        	
        }
        else{   // tag     MifareClassic射频卡
         	
        	Tag rawTag =intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            if (rawTag != null) {
            	 String[]temp = rawTag.getTechList();
                 for(String s :temp){
                   Log.i("xxx","s = "+s);
                 }
            
                 readTechPayloadMC(rawTag);
            }
            
            
        	
        }
        
        
        
        
     /*   
       
        
        Parcelable[] rawID = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_ID);
        if (rawID != null) {

        	NdefMessage[] msgs = new NdefMessage[rawID.length];

            for (int i = 0; i < rawID.length; i++) {

                msgs[i] = (NdefMessage) rawID[i];

            }

        }
        
        */
        
        
        
    }
    
    
    // MifareClassic的射频卡，http://blog.csdn.net/w969272198/article/details/8651517
    private boolean auth;
    private void readTechPayloadMC(Tag tag){
        MifareClassic mc =MifareClassic.get(tag);//通过intent拿到EXTRA_TAG并转化成MirareClassic格式。
        if(mc == null)
        	return;
        
        
        /*
        NfcF.get(tag)
        见到同类型能读出各区块,适配到具体类型的卡片
        */
        
        
        int bCount = 0 ;
        int bIndex = 0 ;
        try {
            mc.connect();
            int sectorCount = mc.getSectorCount();//获得sector总数
            Log.i("liyufei3","sectorCount = "+sectorCount);
            for(int i =0;i<sectorCount;i++){
                //尝试去获得每个sector的认证，只有认证通过才能访问
                auth = mc.authenticateSectorWithKeyA(i,MifareClassic.KEY_DEFAULT);
                if(auth){
                    //这句其实不是必须的，因为每个sector中本来就只有4个block
                    bCount = mc.getBlockCountInSector(i);
                    
                    //all blocks are consecutively numbered ,0-64,so we can not usenumber of cycles to be index.
                    //we just can get the first block in iTH sector

 //我们可以得到每一个sector中的第一个block的编号
                    bIndex = mc.sectorToBlock(i);

                    for(int j=0;j<bCount;j++){//循环四次拿出一个sector中所有的block
 //每次循环bIndex会去++，然后可以得出每一个block的数据。这些数据是字节码，所以你还有一个翻译的工作要做。

                        byte[] data =mc.readBlock(bIndex);
                   //     String s = new String(data,"UTF-8");
                                                
                        String s ="";
                        for(int k=0;k<data.length; k++){
                        	byte t = data[k];
                        	int v = t & 0xFF;  
                            String hv = Integer.toHexString(v);  
                            if(hv.length()<2)
                            	hv = "0"+hv;
                        	s+=hv;  
                        }
                        System.out.println("块"+bIndex+": "+s);
                        bIndex++;
                    }
                }else{
                    Log.i("xxx","   auth = false!!!  in sectorCount = "+i);

                    
                }
            }

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
     }
    

    @Override
    public void onPause() {
        super.onPause();
        if (mAdapter != null) mAdapter.disableForegroundDispatch(this);
    }
}
